// redis.module.ts
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import Redis from "ioredis";
import { RedisService } from "./redis.services";
import { RedisController } from "./redis.controller";

@Module({
  imports: [ConfigModule],
  providers: [
    {
      provide: "REDIS_CLIENT",
      inject: [ConfigService],
      useFactory: (configService: ConfigService): Redis => {
        const redisHost = configService.get<string>("REDIS_HOST", "localhost");
        const redisPort = configService.get<number>("REDIS_PORT", 6379);
        const redisPassword = configService.get<string>("REDIS_PASSWORD");

        // 创建 IORedis 客户端
        const redisClient = new Redis({
          host: redisHost,
          port: redisPort,
          password: redisPassword || undefined,
          db: 0, // 数据库索引
          retryStrategy: (times) => {
            const delay = Math.min(times * 50, 2000);
            return delay;
          },
        });

        // 监听 Redis 连接错误事件
        redisClient.on("error", (error: unknown) => {
          console.error("Redis client error:", error);
        });

        // 监听连接成功事件
        redisClient.on("connect", () => {
          console.log(`Redis client connected to ${redisHost}:${redisPort}`);
        });

        // 监听就绪事件
        redisClient.on("ready", () => {
          console.log("Redis client ready");
        });

        return redisClient;
      },
    },
    RedisService,
  ],
  controllers: [RedisController],
  exports: ["REDIS_CLIENT", RedisService],
})
export class RedisModule {}
